package com.github.ginirohikocha.dbm.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.ginirohikocha.dbm.Address;
import com.github.ginirohikocha.dbm.R;
import com.github.ginirohikocha.dbm.RequestCode;
import com.github.ginirohikocha.dbm.activity.OfferDetailActivity;
import com.github.ginirohikocha.dbm.activity.OrderDetailActivity;
import com.github.ginirohikocha.dbm.entity.Offer;
import com.github.ginirohikocha.dbm.util.HttpUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RecycleOfferAdapter extends RecyclerView.Adapter<RecycleOfferAdapter.OfferHolder> {

    private OrderDetailActivity activity;

    private List<Offer> offers = new ArrayList<>();

    public RecycleOfferAdapter(Context context, String orderNum) {
        this.activity = (OrderDetailActivity)context;
        getOfferData(orderNum);
    }

    @NonNull
    @Override
    public OfferHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_offer , viewGroup , false);
        return new RecycleOfferAdapter.OfferHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final OfferHolder offerHolder, int i) {
        offerHolder.offer = offers.get(i);
        offerHolder.offerTitle.setText(offerHolder.offer.getOfferTitle());
        offerHolder.offerAmount.setText(String.format(Locale.CHINESE, "×%d", offerHolder.offer.getOfferAmount()));
        offerHolder.offerPrice.setText(String.format(Locale.CHINESE, "¥%.2f", offerHolder.offer.getOfferPrice().doubleValue()));
        offerHolder.offerContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, OfferDetailActivity.class);
                intent.putExtra("id", offerHolder.offer.getId());
                activity.startActivityForResult(intent, RequestCode.REQUEST_OFFER_DETAIL);
            }
        });
        if (offerHolder.offer.getOfferStatus().equals("未完成")) {
            initColor(offerHolder, false);
        } else {
            offerHolder.offerStatus.setText(activity.getResources().getString(R.string.yes));
            initColor(offerHolder, true);
        }
    }

    @Override
    public int getItemCount() {
        if (offers == null)
            return 0;
        return offers.size();
    }

    //获取业务内容
    private void getOfferData(String orderNum) {
        activity.setLoading(true);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNum", orderNum);

        HttpUtil.sendOkHttpPostRequest(Address.OFFER_QUERY, RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString()), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Intent result = new Intent();
                result.putExtra("msg", "订单获取失败，请检查网络状态");
                activity.setResult(Activity.RESULT_OK, result);
                activity.setLoading(false);
                activity.finish();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String reponseBody = response.body().string();
                Log.d("业务获取", reponseBody);
                JSONObject responseJson = JSONObject.parseObject(reponseBody);
                JSONArray jsonArray1 = responseJson.getJSONArray("offers");
                if (jsonArray1 != null)
                    offers = jsonArray1.toJavaList(Offer.class);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        notifyDataSetChanged();
                    }
                });
                activity.setLoading(false);
            }
        });
    }

    private void initColor(OfferHolder holder, boolean isCompleted) {
        int color = Color.RED;
        if (isCompleted)
            color = activity.getResources().getColor(R.color.green);
        holder.offerTitle.setTextColor(color);
        holder.offerAmount.setTextColor(color);
        holder.offerPrice.setTextColor(color);
        holder.offerStatus.setTextColor(color);
    }

    //获取总价
    public double getPriceCount() {
        double prcie = 0;
        for (Offer offer: offers) {
            prcie += offer.getOfferPrice().doubleValue();
        }
        return prcie;
    }

    public void refresh(String orderNum) {
        getOfferData(orderNum);
        notifyDataSetChanged();
    }
    /**
     * 业务单元内部类
     * **/
    class OfferHolder extends RecyclerView.ViewHolder {

        private Offer offer;

        private LinearLayout offerContent;
        private ImageView offerImg;
        private TextView offerTitle, offerAmount, offerPrice, offerStatus;

        public OfferHolder(@NonNull View itemView) {
            super(itemView);
            offerContent = itemView.findViewById(R.id.item_offer);
            offerImg = itemView.findViewById(R.id.item_offer_img);
            offerTitle = itemView.findViewById(R.id.item_offer_title);
            offerAmount = itemView.findViewById(R.id.item_offer_amount);
            offerPrice = itemView.findViewById(R.id.item_offer_price);
            offerStatus = itemView.findViewById(R.id.item_offer_status);
        }
    }
}
